package com.xky.ui.module.warehouseManagement.update;

import com.xky.pojo.Warehouses;
import com.xky.utils.DBUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;

public class UpdateWarehouse extends JFrame {
    private JPanel mainPanel, headerPanel, formPanel, buttonPanel;
    private JTextField[] textFields;
    private JComboBox<String> isActiveComboBox;
    private JButton updateButton, queryButton;
    private JLabel statusLabel;
    
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);
    private static final Color QUERY_BUTTON_COLOR = new Color(46, 204, 113);

    public UpdateWarehouse() {
        initializeFrame();
        initComponents();
        setVisible(true);
    }

    private void initializeFrame() {
        setTitle("仓库信息修改");
        setSize(550, 600);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initComponents() {
        // 创建主面板并设置背景渐变
        mainPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                int w = getWidth();
                int h = getHeight();
                GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
                g2d.setPaint(gp);
                g2d.fillRect(0, 0, w, h);
            }
        };
        mainPanel.setLayout(new BorderLayout(10, 10));
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));

        // 1. 头部面板
        createHeaderPanel();

        // 2. 表单面板
        createFormPanel();

        // 3. 按钮面板
        createButtonPanel();
        
        // 4. 状态面板
        createStatusPanel();

        // 添加事件监听
        setupEventListeners();

        add(mainPanel);
    }

    private void createHeaderPanel() {
        headerPanel = new JPanel(new BorderLayout());
        headerPanel.setOpaque(false);
        
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        titlePanel.setOpaque(false);
        
        JLabel titleLabel = new JLabel("仓库信息修改");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        titleLabel.setForeground(PRIMARY_COLOR);
        titlePanel.add(titleLabel);
        
        JPanel hintPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        hintPanel.setOpaque(false);
        
        JLabel hintLabel = new JLabel("请输入仓库ID查询后再修改");
        hintLabel.setFont(new Font("微软雅黑", Font.ITALIC, 14));
        hintLabel.setForeground(Color.GRAY);
        hintPanel.add(hintLabel);
        
        // 添加分隔线
        JSeparator separator = new JSeparator();
        separator.setForeground(PRIMARY_COLOR);
        separator.setPreferredSize(new Dimension(450, 2));
        
        headerPanel.add(titlePanel, BorderLayout.NORTH);
        headerPanel.add(hintPanel, BorderLayout.CENTER);
        headerPanel.add(separator, BorderLayout.SOUTH);
        headerPanel.setBorder(new EmptyBorder(0, 0, 20, 0));
        
        mainPanel.add(headerPanel, BorderLayout.NORTH);
    }

    private void createFormPanel() {
        // 创建带圆角和阴影的面板
        JPanel formCard = createRoundedPanel();
        formCard.setLayout(new BorderLayout());
        
        formPanel = new JPanel(new GridBagLayout());
        formPanel.setOpaque(false);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        String[] labels = {"仓库ID *", "仓库编码 *", "仓库名称 *", "仓库位置 *", "是否启用 *"};
        textFields = new JTextField[4]; // 只需要4个文本框，另一个是下拉框

        Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
        Font fieldFont = new Font("微软雅黑", Font.PLAIN, 16);

        for (int i = 0; i < labels.length; i++) {
            // 添加标签
            gbc.gridx = 0;
            gbc.gridy = i;
            gbc.weightx = 0.3;
            JLabel label = new JLabel(labels[i]);
            label.setFont(labelFont);
            label.setForeground(PRIMARY_COLOR);
            formPanel.add(label, gbc);

            // 添加输入控件
            gbc.gridx = 1;
            gbc.weightx = 0.7;
            
            if (i != 4) { // 不是是否启用
                textFields[i] = new JTextField(20);
                textFields[i].setFont(fieldFont);
                textFields[i].setPreferredSize(new Dimension(250, 35));
                formPanel.add(textFields[i], gbc);
            } else { // 是否启用使用下拉框
                isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
                isActiveComboBox.setFont(fieldFont);
                isActiveComboBox.setPreferredSize(new Dimension(250, 35));
                isActiveComboBox.setBackground(Color.WHITE);
                formPanel.add(isActiveComboBox, gbc);
            }
        }

        
        formCard.add(formPanel, BorderLayout.CENTER);
        formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        mainPanel.add(formCard, BorderLayout.CENTER);
    }

    private void createButtonPanel() {
        buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setOpaque(false);

        queryButton = new JButton("查询");
        styleButton(queryButton, QUERY_BUTTON_COLOR);
        
        updateButton = new JButton("修改");
        styleButton(updateButton, BUTTON_COLOR);

        // 初始状态下修改按钮不可用
        updateButton.setEnabled(false);

        buttonPanel.add(queryButton);
        buttonPanel.add(updateButton);

        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
    }
    
    private void styleButton(JButton button, Color bgColor) {
        button.setFont(new Font("微软雅黑", Font.BOLD, 16));
        button.setPreferredSize(new Dimension(120, 40));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
    }
    
    private void createStatusPanel() {
        JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        statusPanel.setOpaque(false);
        statusPanel.setPreferredSize(new Dimension(Short.MAX_VALUE, 30));
        
        statusLabel = new JLabel(" ");
        statusLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        statusLabel.setForeground(Color.GRAY);
        statusPanel.add(statusLabel);
    }
    
    /**
     * 创建带圆角和阴影的面板
     */
    private JPanel createRoundedPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setColor(Color.WHITE);
                g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
            }
        };
        panel.setOpaque(false);
        
        // 添加阴影边框
        panel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5),
            BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)
            )
        ));
        
        return panel;
    }

    private void setupEventListeners() {
        // 查询按钮事件
        queryButton.addActionListener(e -> {
            String warehouseIdStr = textFields[0].getText().trim();
            if (warehouseIdStr.isEmpty()) {
                JOptionPane.showMessageDialog(this, "请输入仓库ID", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            try {
                int warehouseId = Integer.parseInt(warehouseIdStr);
                queryWarehouseInBackground(warehouseId);
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的数字ID", "输入错误", JOptionPane.WARNING_MESSAGE);
            }
        });

        // 修改按钮事件
        updateButton.addActionListener(e -> {
            try {
                // 首先进行输入校验
                if (!validateInputs()) {
                    return; // 如果校验不通过，直接返回
                }

                Integer warehouseId = Integer.valueOf(textFields[0].getText().trim());
                String warehouseCode = textFields[1].getText().trim();
                String warehouseName = textFields[2].getText().trim();
                String location = textFields[3].getText().trim();
                String isActive = isActiveComboBox.getSelectedIndex() == 0 ? "1" : "0"; // "是"对应1，"否"对应0

                updateWarehouseInBackground(warehouseId, warehouseCode, warehouseName, location, isActive.equals("1"));
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "发生错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
    }

    private void queryWarehouseInBackground(int warehouseId) {
        SwingWorker<Warehouses, Void> worker = new SwingWorker<Warehouses, Void>() {
            @Override
            protected Warehouses doInBackground() throws Exception {
                statusLabel.setText("正在查询...");
                return findWarehouseById(warehouseId);
            }

            @Override
            protected void done() {
                try {
                    Warehouses warehouse = get();
                    if (warehouse != null) {
                        // 填充表单数据
                        textFields[0].setText(String.valueOf(warehouse.getWarehouseId()));
                        textFields[1].setText(warehouse.getWarehouseCode());
                        textFields[2].setText(warehouse.getWarehouseName());
                        textFields[3].setText(warehouse.getLocation());
                        
                        // 设置是否启用下拉框
                        isActiveComboBox.setSelectedIndex(warehouse.getIsActive() ? 0 : 1);

                        // 启用修改按钮
                        updateButton.setEnabled(true);
                        statusLabel.setText("查询成功");
                    } else {
                        JOptionPane.showMessageDialog(UpdateWarehouse.this, "未找到该仓库", "提示", JOptionPane.WARNING_MESSAGE);
                        updateButton.setEnabled(false);
                        statusLabel.setText("未找到仓库");
                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(UpdateWarehouse.this, "查询失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    statusLabel.setText("查询失败");
                }
            }
        };
        worker.execute();
    }

    private void updateWarehouseInBackground(Integer warehouseId, String warehouseCode, String warehouseName, String location, Boolean isActive) {
        SwingWorker<Boolean, Void> worker = new SwingWorker<>() {
            @Override
            protected Boolean doInBackground() throws Exception {
                statusLabel.setText("正在更新...");
                return updateWarehouse(warehouseId, warehouseCode, warehouseName, location, isActive);
            }

            @Override
            protected void done() {
                try {
                    boolean success = get();
                    if (success) {
                        JOptionPane.showMessageDialog(UpdateWarehouse.this, "仓库信息更新成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                        dispose();
                    } else {
                        JOptionPane.showMessageDialog(UpdateWarehouse.this, "仓库信息更新失败", "错误", JOptionPane.ERROR_MESSAGE);
                        statusLabel.setText("更新失败");
                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(UpdateWarehouse.this, "更新失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    statusLabel.setText("更新失败: " + e.getMessage());
                }
            }
        };
        worker.execute();
    }

    private boolean validateInputs() {
        // 1. 校验仓库ID
        if (textFields[0].getText().trim().isEmpty()) {
            showValidationError("仓库ID不能为空");
            return false;
        }
        
        try {
            Integer.parseInt(textFields[0].getText().trim());
        } catch (NumberFormatException e) {
            showValidationError("仓库ID必须是数字");
            return false;
        }
        
        // 2. 校验仓库编码
        if (textFields[1].getText().trim().isEmpty()) {
            showValidationError("仓库编码不能为空");
            return false;
        }
        
        // 3. 校验仓库名称
        if (textFields[2].getText().trim().isEmpty()) {
            showValidationError("仓库名称不能为空");
            return false;
        }
        
        // 4. 校验仓库位置
        if (textFields[3].getText().trim().isEmpty()) {
            showValidationError("仓库位置不能为空");
            return false;
        }
        
        // 所有校验通过
        return true;
    }

    private void showValidationError(String message) {
        JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
        statusLabel.setText("验证错误: " + message);
    }

    private Warehouses findWarehouseById(int warehouseId) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement("SELECT * FROM warehouses WHERE warehouse_id = ?");
            preparedStatement.setInt(1, warehouseId);
            resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                Warehouses warehouse = new Warehouses();
                warehouse.setWarehouseId(resultSet.getInt("warehouse_id"));
                warehouse.setWarehouseCode(resultSet.getString("warehouse_code"));
                warehouse.setWarehouseName(resultSet.getString("warehouse_name"));
                warehouse.setLocation(resultSet.getString("location"));
                warehouse.setIsActive("1".equals(resultSet.getString("is_active")));
                return warehouse;
            }
            return null;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, resultSet);
        }
    }

    private boolean updateWarehouse(Integer warehouseId, String warehouseCode, String warehouseName, String location, Boolean isActive) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement(
                    "UPDATE warehouses SET warehouse_code = ?, warehouse_name = ?, location = ?, is_active = ?, updated_time = NOW() WHERE warehouse_id = ?");
            preparedStatement.setString(1, warehouseCode);
            preparedStatement.setString(2, warehouseName);
            preparedStatement.setString(3, location);
            preparedStatement.setString(4, isActive ? "1" : "0");
            preparedStatement.setInt(5, warehouseId);

            return preparedStatement.executeUpdate() > 0;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(UpdateWarehouse::new);
    }
} 